from app.libs.httper import HTTP
from flask import current_app
#存放着原始的图书数据
class YuShuBook:
    #模型层 MVC M层
    isbn_url = 'http://127.0.0.1:2000/isbn/{}'
    keyword_url = 'http://127.0.0.1:2000/keyword?q={}&count={}&start={}'
    def __init__(self):
        self.total=0
        self.books=[]
    def __fill_single(self,data):#单本 isbn搜索
        if data:
            self.total=1
            self.books.append(data)
    def __fill_collection(self,data):#多本 关键字搜索
        self.total=data['total']
        self.books=data['books']

    def search_by_isbn(self, isbn):
        url = self.isbn_url.format(isbn)
        result = HTTP.get(url)
        #后期改写，把读到的数据缓存到数据库
        self.__fill_single(data=result)

    def search_by_keyword(self, keyword, page=1):
        print(current_app.config['PER_PAGE'])
        #config['PER_PAGE'] 字典[] 别写成()
        url = self.keyword_url.format(keyword, current_app.config['PER_PAGE'], self.calculate_start(page))
        result = HTTP.get(url)
        self.__fill_collection(data=result)


    def calculate_start(self,page):
        return (page - 1) * current_app.config['PER_PAGE']

    @property
    def first(self):
        return self.books[0] if self.total>=1 else None
